
package com.joysuch.wwyt.core.listener;

import java.util.Date;
import java.util.Locale;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.baidu.aip.face.AipFace;
import com.joysuch.wwyt.audit.service.AuditLogActionDefService;
import com.joysuch.wwyt.baidu.req.BaiduSample;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.util.ApplicationContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebListener
public class StartupListener implements ServletContextListener {

    private static final Logger logger = LoggerFactory.getLogger(StartupListener.class);

    @Autowired
    private AuditLogActionDefService auditLogActionDefService;

    @Autowired
    private BaseConfigService baseConfigService;

    public static AipFace client;
    public StartupListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 设置本地化
        Locale.setDefault(Locale.SIMPLIFIED_CHINESE);

        logger.info("context initialized " + new Date());
        ApplicationContextHolder.setApplicationContext(WebApplicationContextUtils.findWebApplicationContext(sce.getServletContext()));
        auditLogActionDefService.loadAll();
        Boolean flag = baiduInit();
        if (flag){
            groupAdd();
        }
//        BaiduSample.init();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    public  Boolean baiduInit(){
        boolean flag=false;
        String appId="";
        String key="";
        String secret="";;
        BaseConfig appIdConfig = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_ID);
        if (appIdConfig==null || StringUtils.isBlank(appIdConfig.getValue())) {
         return flag;
        }
        BaseConfig appKeyConfig = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_KEY);
        if (appKeyConfig==null&& StringUtils.isBlank(appKeyConfig.getValue())) {
         return flag;
        }
        BaseConfig appSecretConfig = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_SECRET);
        if (appSecretConfig==null&&StringUtils.isBlank(appSecretConfig.getValue())) {
           return flag;
        }
        appId=appIdConfig.getValue();
        key=appKeyConfig.getValue();
        secret=appSecretConfig.getValue();
        client = new AipFace(appId, key, secret);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        BaiduSample.client=client;
        BaiduSample.APP_ID=appId;
        BaiduSample.SECRET_KEY=secret;
        BaiduSample.API_KEY=key;
        flag=true;
       return flag;
    }

    //创建用户组
    public void groupAdd(){
        String groupId="1_001_001";
        BaseConfig buildIdConfig = baseConfigService.findConfig(BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
        if (buildIdConfig!=null ) {
//            String orgCode=appIdConfig.getOrgCode().replaceAll("-","_");
            groupId=buildIdConfig.getValue();
        }
        try {
            JSONObject jsonObject = client.getGroupList(null);
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray array = result.getJSONArray("group_id_list");
            if (array!=null) {
                for (Object o : array) {
                    if (o.toString().equals(groupId)){
                       return;
                    }
                }
            }
            client.groupAdd(groupId,null);
        } catch (JSONException e) {
            logger.error("百度人脸识别添加用户组失败");
            e.printStackTrace();
        }
    }
}
